// components/fileUploadComponent/fileUploadComponent.js
var util = require('../../utils/util.js')
var _this
Component({
  /**
   * 组件的属性列表
   */
  properties: {

  },

  /**
   * 组件的初始数据
   */
  data: {
    filePath: ''
  },
  attached: function () {
    _this = this
  },
  /**
   * 组件的方法列表
   */
  methods: {
    chooseImage: () => {
      wx.chooseImage({
        count: 1,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success(res) {
          // tempFilePath可以作为img标签的src属性显示图片
          const tempFilePaths = res.tempFilePaths
          console.log(tempFilePaths)
          _this.setData({
            filePath: tempFilePaths
          })
        },
        fail() {
          _this.setData({
            filePath: ''
          })
        }
      })
    },
    requestDidResponse: (res) => {
      wx.hideLoading()
      var data = JSON.parse(res)
      if (data.status == '200') {
        _this.triggerEvent('uploadFinishedHandle', {'action':1}, {})
      } else {
        wx.showToast({
          title: '上传失败',
          icon: 'none'
        })
      }
    },
    requestDidFaild: (res) => {
      wx.hideLoading()
      console.log(res)
      wx.showToast({
        title: '网络异常',
        icon: 'none'
      })
    },
    fileUpload: (e) => {

    },
    finishedHandle: function (e) {
      if (e.detail.action == 1) {
        if (_this.data.filePath == '') {
          wx.showToast({
            title: '请选择一张靓照吧',
            icon: 'none'
          })
          return
        }
        util.fileUpload(_this.requestDidResponse, _this.requestDidFaild, _this.data.filePath[0])
        wx.showLoading({
          title: '正在上传',
        })
      } else{
        _this.triggerEvent('uploadFinishedHandle', e.detail, {})
      }
    },
  }
})
